import com.bitsinharmony.recognito.MatchResult;
import com.bitsinharmony.recognito.Recognito;
import common.ServerResponse;
import curb.VoiceController;
import factory.RecogntioFactory;
import lombok.extern.slf4j.Slf4j;
import util.PropertiesUtil;

import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by Administrator on 2021/4/13.
 */
@Slf4j
public class Run {
    public static void main(String[] args) {
        Recognito<String> recognito = RecogntioFactory.getRecognito(48000.0f);

        //获取全部声纹
        VoiceController.getAllVoicePrint();

        List<MatchResult<String>> matches = null;
        while (true){
            File file = new File(PropertiesUtil.getProperty("file.catalog"));

            int temp = 1;
            while (true){
                if (!file.exists()){
                    if (temp == 1){
                        System.out.println("等待录音文件");
                        temp = 0;
                    }
                }else{
                    break;
                }
            }


            try {
                matches = recognito.identify(file);
            } catch (UnsupportedAudioFileException e) {
                log.error("不支持的声音类型", e);
            } catch (IOException e) {
                log.error("传输错误", e);
            }
            MatchResult<String> match = matches.get(0);



            //如果匹配度大于97就打卡成功
            if(match.getLikelihoodRatio() >= 97) {
                ServerResponse serverResponse = VoiceController.createAttendance(match.getKey());
                if (serverResponse.isSuccess()){
                    System.out.println(match.getKey() + "欢迎回来，" + serverResponse.getData() + "匹配度" + match.getLikelihoodRatio() + "%.");
                }

                /*try {
                    recognito.mergeVoiceSample(match.getKey(), file);
                } catch (UnsupportedAudioFileException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }*/
            }else{
                System.out.println("没有成功，请再试试 " + match.getKey() + "  " + match.getLikelihoodRatio() + "%");
            }

            file.delete();
        }


    }
}
